package zhtt01.mysql.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import zhtt01.mysql.entity.Organization;
import zhtt01.mysql.repository.OrganizationRepository;

import java.util.List;

@Service
public class OrganizationService {

    @Autowired
    private OrganizationRepository organizationRepository;

    public Organization update(Organization organization){
        organizationRepository.saveAndFlush(organization);
        return organization;
    }

    public Organization save(Organization organization){
        organizationRepository.save(organization);
        return organization;
    }

    public boolean delete(long id){
     organizationRepository.deleteById(id);
     return true;
    }

    public Organization get(long id){
        return organizationRepository.getOne(id);
    }

    /* 查询子机构 */
    public List<Organization> getOrgByPId(Long parentId,Long id){
        if(parentId==null && id ==null){
            return organizationRepository.getRootOrganizationList();
        }else if(parentId==null && id !=null){
            return organizationRepository.getRootOrganizationList(id);
        }else if(parentId!=null && id ==null){
            return organizationRepository.getOrgByPId(parentId);
        }else{
            return organizationRepository.getOrgByPId(parentId,id);
        }
    }

    public Page<Organization> paging(int pageIndex,int pageSize){
        Sort sort=new Sort(Sort.Direction.DESC,"createTime");
        PageRequest pageRequest=PageRequest.of(pageIndex,pageSize,sort);
        Page<Organization> orgList= organizationRepository.findAll(pageRequest);
        return orgList;
    }
}
